package array.passed;

public class SearchForARange {

	/**
	Given a sorted array of integers, find the starting and ending position of a given target value.

	Your algorithm's runtime complexity must be in the order of O(log n).

	If the target is not found in the array, return [-1, -1].

	For example,
	Given [5, 7, 7, 8, 8, 10] and target value 8,
	return [3, 4].
	 */
	public int[] searchRange(int[] A, int target) {
		// Start typing your Java solution below
		// DO NOT write main() function
		int[] results = new int[2];
		results[0] = searchRangeHelper(A, target, true);
		results[1] = searchRangeHelper(A, target, false);
		return results;
	}

	public int searchRangeHelper(int[] A, int target, boolean isLeft) {
		if (A == null || A.length == 0)
			return -1;

		int left = 0, right = A.length - 1, result = -1;
		while (left <= right) {
			int mid = left + (right - left) / 2;
			if (target < A[mid]) {
				right = mid - 1;
			} else if (target > A[mid]) {
				left = mid + 1;
			} else {
				result = mid;
				if (isLeft)
					right = mid - 1;
				else
					left = mid + 1;
			}
		}

		return result;
	}

	public SearchForARange() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
